package errors

import (
	"net/http"

	"github.com/labstack/echo/v4"
)

type ResponseHTTP struct {
	StatusCode int    `json:"statusCode"`
	Message    string `json:"message"`
}

const defaultHTTPCode = http.StatusInternalServerError

var httpStatuses = map[ErrorType]int{
	ErrInternalError:        http.StatusInternalServerError,
	ErrInvalidArgs:          http.StatusBadRequest,
	ErrNoAccess:             http.StatusForbidden,
	ErrNotFound:             http.StatusNotFound,
	ErrMethodNotImplemented: http.StatusNotImplemented,
	ErrConflict:             http.StatusConflict,
	ErrInsufficientFunds:    http.StatusPaymentRequired,
}

var clientErrors = map[int]error{
	http.StatusInternalServerError: ErrInternalError,
	http.StatusBadRequest:          ErrInvalidArgs,
	http.StatusNotImplemented:      ErrMethodNotImplemented,
	http.StatusNotFound:            ErrNotFound,
	http.StatusForbidden:           ErrNoAccess,
}

func ErrorTypeHTTP(statusCode int) error {
	errorType, ok := clientErrors[statusCode]
	if !ok {
		return ErrInternalError
	}

	return errorType
}

func HTTP(ctx echo.Context, err Error) error {
	status, ok := httpStatuses[err.Type()]
	if !ok {
		return ctx.JSON(http.StatusInternalServerError, ResponseHTTP{
			StatusCode: defaultHTTPCode,
			Message:    err.Error(),
		})
	}

	return ctx.JSON(status, ResponseHTTP{
		StatusCode: status,
		Message:    err.Error(),
	})
}
